import time
import xml.etree.ElementTree as ET
import copy
class ReportHandle:
    '''
    处理sumo输出的trip.out.xml文件，得到停车延误,停车次数和行程时间
    '''
    def Sumo_DelayStatistic(name):
        try:
            tree = ET.parse('.\\%s'%(name))
            root = tree.getroot()
            veh_num = 0
            waitingtime_SUM = 0
            waitingcount_SUM = 0
            duration_SUM = 0
            for item in root.findall('tripinfo'):
                veh_num += 1
                waitingtime = item.attrib['waitingTime']
                waitingcount = item.attrib['waitingCount']
                duration = item.attrib['duration']
                waitingtime_SUM += float(waitingtime)
                waitingcount_SUM += float(waitingcount)
                duration_SUM += float(duration)
            return ('路网车辆平均停车延误:'+str(waitingtime_SUM/veh_num),
                    '路网车辆平均停车次数:'+str(waitingcount_SUM/veh_num),
                    '路网车辆平均行程时间:' + str(duration_SUM / veh_num))

        except:
            pass

    def Sumo_QueueStatistic(name):
        '''
        处理sumo输出的queue.out.xml文件，得到路网所有车道的平均排队长度和最大排队长度
        '''
        try:
            tree = ET.parse('.\\%s'%(name))
            root = tree.getroot()
            i = 0
            laneid_queue = {}
            laneid_queue_avg = {}
            for item in root.findall('data'):
                i += 1
                for lanes in item.findall('lanes'):
                    for lane in lanes.findall('lane'):
                        if lane.attrib['id'] not in laneid_queue.keys():
                            laneid_queue[lane.attrib['id']] = []
                        else:
                            laneid_queue[lane.attrib['id']].append(float(lane.attrib['queueing_length']))
            laneid_queue_avg = copy.deepcopy(laneid_queue)
            # 输出每条lane的平均排队长度
            for j in laneid_queue_avg:
                laneid_queue_avg[j] = list(map(float, laneid_queue_avg[j]))
                laneid_queue_avg[j] = str(sum(laneid_queue_avg[j]) / i)
            print('路网每条lane的平均排队长度:' + str(laneid_queue_avg))
            # 输出每条lane的最大排队长度
            for k in laneid_queue:
                laneid_queue[k] = str(max(laneid_queue[k]))
            return '路网每条lane的最大排队长度:' + str(laneid_queue)
        except:
            pass
a = input("请输入路网车辆行驶报告文件名:")
b = input("请输入路网车辆排队长度报告文件名:")
print(ReportHandle.Sumo_DelayStatistic(a))
print(ReportHandle.Sumo_QueueStatistic(b))
time.sleep(99999)

